local WebSockets = require(SCRIPTS_DIR .. ".network.WebSockets");
local WebNet = class("WebNet")
function WebNet:ctor()
    -- body
    self.messageType = WebSockets.TEXT_MESSAGE;
    self.websocket = nil;
    self.socketIsOk = false;
end

function WebNet:connectSocket(host,protocol)
    -- body
    if self.websocket then return end
    self.websocket = WebSockets.new(host,protocol);
    self.websocket:addEventListener(WebSockets.OPEN_EVENT, handler(self, self.onOpen));
    self.websocket:addEventListener(WebSockets.MESSAGE_EVENT, handler(self, self.onMessage));
    self.websocket:addEventListener(WebSockets.CLOSE_EVENT, handler(self, self.onClose));
    self.websocket:addEventListener(WebSockets.ERROR_EVENT, handler(self, self.onError));
end

function WebNet:onOpen()
    -- body
    mgrs.log:printNotice("WebSocketMgr:onOpen")
    self.socketIsOk = true;
    mgrs.proto:socketSucess();
    --mgrs.event:dispatchEvent({name = enums.Event.WebSocketOpen});
end

function WebNet:onMessage()
    -- body
    if WebSockets.BINARY_MESSAGE == event.messageType then
        mgrs.log:printNotice("receive binary msg: len = %s, binary = %s", string.len(event.message), bin2hex(event.message));
    else
        mgrs.log:printNotice("收到数据:%s",event.message)
        local message = json.decode(event.message);
        mgrs.proto:receive(message.msgid,message);
    end
end

function WebNet:onClose()
    -- body
    mgrs.log:printNotice("WebSocketMgr:onClose");
    self.websocket = nil
    self.socketIsOk = false;
    mgrs.proto:socketClosed();
end

function WebNet:onError()
    -- body
     mgrs.log:printWarn("WebSocket onError %s", event.error)
    self.websocket = nil
    self.socketIsOk = false;
    mgrs.proto:socketError();
end


function WebNet:closeSocket()
    -- body
    if self.websocket then
        self.websocket:close();
    end
end

function WebNet:sendData(data)
    -- body
    if self.websocket and self.socketIsOk then
        if type(data) == "table" then
            data = json.encode(data);
        elseif type(data) == "number" then
            data = json.encode({msgid = data});
        end
        mgrs.log:printNotice("发送数据:%s",data);
        self.websocket:send(data,self.messageType);
    end
end

return WebNet;